#include<stdlib.h>
#include<stdio.h>
#include <pthread.h>
#include "ConfigStruct.h"

void *print_message_function( void *ptr );
void call_threads();
void *thread_controller( void *ptr );

int main(int argc, char ** argv)
{
    struct ConfigStruct configuration;


    if(argc != 2)
    {
        printf("Usage:\t");
        printf("test <config_file>\n");
        return;
    }

    printf("Using config file: %s\n", argv[1]);

    ReadConfig(argv[1], &configuration);

    /*
    printf("laddress: %s\n", configuration.laddress);
    printf("raddress: %s\n", configuration.raddress);
    printf("num_rounds: %d\n", configuration.num_rounds);
    printf("packet_size: %d\n", configuration.packet_size);
    printf("num_tests: %d\n", configuration.num_tests);
    printf("test_to_run: %s\n", configuration.test_to_run);
*/

    call_threads(configuration);

}


void call_threads(struct ConfigStruct config)
{
	pthread_t thread1, thread2;
	int  iret1, iret2, i;

	/* Create independent threads each of which will execute function */

	for(i = 0; i < config.num_threads; i ++)
	{

		pthread_t thread;
		struct ConfigStruct config1 = config;//make copies
		config1.thread_id = i;
		pthread_create( &thread, NULL, thread_controller, (void*) &config1);

		pthread_join( thread, NULL);
	}

}
 
void *thread_controller( void *ptr )
{

	struct ConfigStruct *config = (struct ConfigStruct *) ptr;
	if(strstr(config->test_to_run, "sping") != NULL)
	{
		run_sping(config);
	}
	else
	{

		run_flooder(config);
	}
}


void run_flooder(struct ConfigStruct *config)
{
	char command[1000];
	char temp[10];
	strcpy(command, config->test_to_run);
	strcat(command, " -a ");
	strcat(command, config->raddress);
	strcat(command, " -o ");
	strcat(command, config->laddress);
	strcat(command, " -s ");
	strcat(command, " -v ");
	strcat(command, " -n ");
	sprintf(temp, "%d", config->num_rounds);
	strcat(command, temp);
	strcat(command, " > ");
	strcat(command, " log");

	sprintf(temp, "%d", config->thread_id);
	strcat(command, temp);

	strcat(command, ".txt");
	strcat(command, "\n");
	//printf("command is\n%s\n", command);   
	system(command);
}

void run_sping(struct ConfigStruct *config)
{
	char command[1000];
	char temp[10];
	strcpy(command, config->test_to_run);
	strcat(command, " -a ");
	strcat(command, config->raddress);
	strcat(command, " -l ");
	strcat(command, config->laddress);
	strcat(command, " -s ");
	strcat(command, " -n ");
	sprintf(temp, "%d", config->num_rounds);
	strcat(command, temp);
	strcat(command, " > ");
	strcat(command, " log");

	sprintf(temp, "%d", config->thread_id);
	strcat(command, temp);

	strcat(command, ".txt");
	strcat(command, "\n");
	//printf("command is\n%s\n", command);   
	system(command);
}

